<?php
/*
 * This file is part of the sfPropel13Plugin package.
 * (c) 2007 Joshua May <notjosh@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

class sfPropel13AdminGenerator extends sfPropel13CrudGenerator
{

  public function getPrimaryKeyUrlParamsForDetails($prefix = '')
  {
    $params = array();
    $i = 1;
    foreach ($this->getPrimaryKey() as $pk)
    {
      $phpName   = $pk->getPhpName();
      $fieldName = sfInflector::underscore($phpName);
      $params[]  = "pk_for_details='.".$this->getColumnGetter($pk, true, $prefix);
      $i++;
    }

    return implode(".'&", $params);
  }
  
  public function getPrimaryKeyUrlParamsForFunction($prefix = '')
  {
    $params = array();
    $i = 1;
    foreach ($this->getPrimaryKey() as $pk)
    {
      $phpName   = $pk->getPhpName();
      $fieldName = sfInflector::underscore($phpName);
      $params[]  = $this->getColumnGetter($pk, true, $prefix);
      $i++;
    }

    return implode('".', $params);
  }

  public function getColumnsForFilters($paramName)
  {
    $phpNames = array();

    // user has set a personnalized list of fields?
    $fields = $this->getParameterValue($paramName);
    if (is_array($fields))
    {


      foreach ($fields as $field)
      {
        list($field, $flags) = $this->splitFlag($field);

        $phpNames[] = $this->getAdminColumnForField($field, $flags);
      }
    }
    else
    {
      // no, just return the full list of columns in table
      return $this->getAllColumns();
    }

    return $phpNames;
  }

    /**
   * Returns HTML code for an action link.
   *
   * @param string  The action name
   * @param array   The parameters
   * @param boolean Whether to add a primary key link or not
   *
   * @return string HTML code
   */
public function getLinkToActionAjax($actionName, $params, $pk_link = false)
{

    $options = isset($params['params']) ? sfToolkit::stringToArray($params['params']) : array();
    	// default values
	$optionsajax=false;
	if ($actionName[0] == '_')
	{
		$actionName = substr($actionName, 1);
		$name       = $actionName;
		$icon       = sfConfig::get('sf_admin_web_dir').'/images/'.$actionName.'_icon.png';
		$action     = $actionName;
		
		if ($actionName == 'delete')
		{
			//$optionsajax['post'] = true;
			if (!isset($optionsajax['confirm']))
			{
				$optionsajax['confirm'] = 'Realmente desea eliminarlo?';
			}
			$optionsajax['200'] = 'restarNumeroResultados(1);alert("El registro fue eliminado correctamente");Element.remove("tr_'. $this->getSingularName() . '\'.'.'$'. $this->getSingularName().'->getId() .\''.'")';
			$optionsajax['405'] = 'alert("El registro no pudo ser eliminado, tiene detalles asociados")';
			$optionsajax['404'] = 'alert("El registro no pudo ser eliminado, el registro fue eliminado con anterioridad")';
			$optionsajax['method'] = 'POST';
 		}
	}
	else
	{
		$name   = isset($params['name']) ? $params['name'] : $actionName;
		$icon   = isset($params['icon']) ? sfToolkit::replaceConstants($params['icon']) : sfConfig::get('sf_admin_web_dir').'/images/default_icon.png';
		$action = isset($params['action']) ? $params['action'] : 'List'.sfInflector::camelize($actionName);
	}
	$url_params = $pk_link ? '?'.$this->getPrimaryKeyUrlParams() : '\'';
	if (!$optionsajax['method']) {$optionsajax['method'] = 'GET';}
	
    $div_update = "div_panel_contenido";
    if(isset($optionsajax['div_update']))$div_update = $optionsajax['div_update'];
    unset($optionsajax['div_update']);
    
      
	if($actionName != 'delete')
	$optionsajax['update'] = array("success"=>"'.\$div_update.'", "failure" => "div_error");
	$optionsajax['url'] = $this->getModuleName().'/'.$action.$url_params .".'&'.\$params_tabs.'";


	$phpOptions = var_export($options, true);
	//$phpOptions = preg_replace("/'confirm' => '(.+?)(?<!\\\)'/", '\'confirm\' => __(\'$1\')', $phpOptions);

	$phpOptionsajax = var_export($optionsajax, true);
	$phpOptionsajax = str_replace("\'","'",$phpOptionsajax);
	$phpOptionsajax = preg_replace("/'confirm' => '(.+?)(?<!\\\)'/", '\'confirm\' => __(\'$1\')', $phpOptionsajax);

	return '<li>[?php echo link_to_remote(image_tag(\''.$icon.'\', array(\'alt\' => __(\''.$name.'\'), \'title\' => __(\''.$name.'\'))),' . "\n" . $phpOptionsajax . "\n" . ($options ? ', '.$phpOptions : '').') ?]</li>'."\n";
}

public function getLinkToActionWindowAjax($actionName, $params, $pk_link = false)
{

    $options = isset($params['params']) ? sfToolkit::stringToArray($params['params']) : array();
    // default values
	$optionsajax=false;
	if ($actionName[0] == '_')
	{
		$actionName = substr($actionName, 1);
		$name       = $actionName;
		$icon       = sfConfig::get('sf_admin_web_dir').'/images/'.$actionName.'_icon.png';
		$action     = $actionName;
		
		if ($actionName == 'delete')
		{
			//$optionsajax['post'] = true;
			if (!isset($optionsajax['confirm']))
			{
				$optionsajax['confirm'] = 'Realmente desea eliminarlo?';
			}
			$optionsajax['200'] = 'restarNumeroResultados(1);Element.remove("tr_'. $this->getSingularName() . '\'.'.'$'. $this->getSingularName().'->getId() .\''.'")';
			$optionsajax['method'] = 'POST';
 		}
	}
	else
	{
		$name   = isset($params['name']) ? $params['name'] : $actionName;
		$icon   = isset($params['icon']) ? sfToolkit::replaceConstants($params['icon']) : sfConfig::get('sf_admin_web_dir').'/images/default_icon.png';
		$action = isset($params['action']) ? $params['action'] : 'List'.sfInflector::camelize($actionName);
	}
	$url_params = $pk_link ? '?'.$this->getPrimaryKeyUrlParams() : '\'';
	if (!$optionsajax['method']) {$optionsajax['method'] = 'GET';}
	$optionsajax['update'] = array("success"=>"div_edicion", "failure" => "div_error");
	$optionsajax['url'] = $this->getModuleName().'/'.$action.$url_params .".'";

	$phpOptions = var_export($options, true);
	$phpOptionsajax = var_export($optionsajax, true);
	$phpOptionsajax = str_replace("\'","'",$phpOptionsajax);
	$phpOptionsajax = preg_replace("/'confirm' => '(.+?)(?<!\\\)'/", '\'confirm\' => __(\'$1\')', $phpOptionsajax);

    return '<li>[?php echo link_to_prototype_window_ajax(image_tag(\''.$icon.'\', array(\'alt\' => __(\''.$name.'\'), \'title\' => __(\''.$name.'\'))), "win_id", '.$phpOptionsajax.' '.($options?', '.$phpOptions:'').') ?]';

}


public function getButtonToActionWindowAjax($actionName, $params, $pk_link = false)
{

    $options = isset($params['params']) ? sfToolkit::stringToArray($params['params']) : array();
    // default values
	$optionsajax=false;
	
    if ($actionName[0] == '_')
    {
      $actionName     = substr($actionName, 1);
      $default_name   = strtr($actionName, '_', ' ');
      $default_icon   = sfConfig::get('sf_admin_web_dir').'/images/'.$actionName.'_icon.png';
      $default_action = $actionName;
      $default_class  = 'sf_admin_action_'.$actionName;

      if ($actionName == 'save' || $actionName == 'save_and_add' || $actionName == 'save_and_list')
      {
        $method = 'submit_tag';
        $options['name'] = $actionName;
      }

      if ($actionName == 'delete')
      {
        $options['post'] = true;
        if (!isset($options['confirm']))
        {
          $options['confirm'] = 'Are you sure?';
        }

        $li_class = 'float-left';

        $only_for = 'edit';
		$optionsajax['method'] = 'POST';
      }
    }
    else
    {
      $default_name   = strtr($actionName, '_', ' ');
      $default_icon   = sfConfig::get('sf_admin_web_dir').'/images/default_icon.png';
      $default_action = 'List'.sfInflector::camelize($actionName);
      $default_class  = '';
    }
    
    $name   = isset($params['name']) ? $params['name'] : $default_name;
    unset($options['name']);
    $icon   = isset($params['icon']) ? sfToolkit::replaceConstants($params['icon']) : $default_icon;
    $action = isset($params['action']) ? $params['action'] : $default_action;
    $url_params = "";
    if($pk_link)$url_params = $pk_link ? '?'.$this->getPrimaryKeyUrlParams().'.\'' : '.\'';
    
	if (!$optionsajax['method']) {$optionsajax['method'] = 'GET';}
	//$optionsajax['update'] = array("success"=>"div_edicion", "failure" => "div_error");
	$optionsajax['url'] = $this->getModuleName().'/'.$action.$url_params;

	$phpOptions = var_export($options, true);
	$phpOptionsajax = var_export($optionsajax, true);
	$phpOptionsajax = str_replace("\'","'",$phpOptionsajax);
	$phpOptionsajax = preg_replace("/'confirm' => '(.+?)(?<!\\\)'/", '\'confirm\' => __(\'$1\')', $phpOptionsajax);

    return '<li>[?php echo button_to_prototype_window_ajax(__(\''.$name.'\'), \'win_id\', '.$phpOptionsajax.' '.($options?', '.$phpOptions:'').') ?]';

}


  /**
   * Returns HTML code for an action button.
   *
   * @param string  The action name
   * @param array   The parameters
   * @param boolean Whether to add a primary key link or not
   *
   * @return string HTML code
   */
  public function getButtonToActionAjax($actionName, $params, $pk_link = false)
  {
    $link_to = isset($params['link_to'])?$params['link_to']:false; 
    unset($params['link_to']);
    
    $params   = (array) $params;
    $options  = isset($params['params']) ? sfToolkit::stringToArray($params['params']) : array();
    $optionsajax  = isset($params['params_ajax']) ? sfToolkit::stringToArray($params['params_ajax']) : array();
    $method   = 'button_to_remote';
    $li_class = '';
    //$optionsajax=false;
    // default values
    if ($actionName[0] == '_')
    {
      $actionName     = substr($actionName, 1);
      $default_name   = strtr($actionName, '_', ' ');
      $default_icon   = sfConfig::get('sf_admin_web_dir').'/images/'.$actionName.'_icon.png';
      $default_action = $actionName;
      $default_class  = 'sf_admin_action_'.$actionName;

      if ($actionName == 'save' || $actionName == 'save_and_add' || $actionName == 'save_and_list')
      {
        $method = 'submit_tag';
        $options['name'] = $actionName;
      }

      if ($actionName == 'delete')
      {
        if (!isset($optionsajax['confirm']))
        {
          $optionsajax['confirm'] = 'Are you sure?';
        }
        $li_class = 'float-left';
        $only_for = 'edit';
		$optionsajax['200'] = 'alert(\"Ok\");';
		$optionsajax['404'] = 'alert(\"Ocurrio un error\")';
		$optionsajax['method'] = 'POST';
      }
    }
    else
    {
      $default_name   = strtr($actionName, '_', ' ');
      $default_icon   = sfConfig::get('sf_admin_web_dir').'/images/default_icon.png';
      $default_action = 'List'.sfInflector::camelize($actionName);
      $default_class  = '';
    }
    $name   = isset($params['name']) ? $params['name'] : $default_name;
    $icon   = isset($params['icon']) ? sfToolkit::replaceConstants($params['icon']) : $default_icon;
    $action = isset($params['action']) ? $params['action'] : $default_action;
    $url_params = "";
    if($pk_link)
    $url_params =  $pk_link ?'?'.$this->getPrimaryKeyUrlParams().'.\'':'.\'';

    if (!isset($options['class']))
    {
      if ($default_class)
      {
        $options['class'] = $default_class;
      }
      else
      {
        $options['style'] = 'background: #ffc url('.$icon.') no-repeat 3px 2px';
      }
    }

    $li_class = $li_class ? ' class="'.$li_class.'"' : '';
    $html = '<li'.$li_class.'>';
     if (!isset($optionsajax['method'])) {$optionsajax['method'] = 'GET';}
     
     if ($method == 'submit_tag')
     {
        $optionsajax['method'] = 'POST';
     }
     if (isset($optionsajax['confirm']) )
     {
        if(strlen("".$optionsajax['confirm']) < 3)
        $optionsajax['confirm'] = "Realmente desea guardar los cambios";
     }

    if(!isset($optionsajax['before']))$optionsajax['before'] = "";

    $div_update = "div_panel_contenido";
    if(isset($optionsajax['div_update']))$div_update = $optionsajax['div_update'];
    unset($optionsajax['div_update']);
    
	$optionsajax['before'] = $optionsajax['before'].'if($("accion_formulario")){ $("accion_formulario").value="'.$actionName.'";}';
    $optionsajax['update'] = array("success"=>"'.\$div_update.'", "failure" => "div_error");

    if($action == "save_and_add")$action="save";
	$optionsajax['url'] = $this->getModuleName().'/'.$action.$url_params;
	$phpOptionsajax = var_export($optionsajax, true);
	$phpOptionsajax = str_replace("\'","'",$phpOptionsajax);
	$phpOptionsajax = preg_replace("/'confirm' => '(.+?)(?<!\\\)'/", '\'confirm\' => __(\'$1\')', $phpOptionsajax);

    if ($method == 'submit_tag')
    {
      $html .= '[?php echo submit_to_remote(\''.$actionName.'\', \''.$name.'\', '.$phpOptionsajax.', '.var_export($options, true).' ) ?]';
    }
    else
    {
        if($link_to != false)
        {
        $phpOptions = var_export($options, true);
        $options['onclick'] = $options['onclick']."('".$this->getModuleName()."/".$action."','\".".$this->getPrimaryKeyUrlParamsForFunction().".\"')";
        $html .= '[?php echo button_to_function("'.$name.'", "'.$options['onclick'].'") ?]';
        }else
        {
        $phpOptions = var_export($options, true);
        $html .= '[?php echo button_to_remote(__(\''.$name.'\'), '.$phpOptionsajax.', '.$phpOptions.') ?]';
        }
    }
    $html .= '</li>'."\n";
    return $html;
  }

  /**
   * Initializes the current sfGenerator instance. 
   *
   * @param sfGeneratorManager A sfGeneratorManager instance
   */
  public function initialize($generatorManager)
  {
    parent::initialize($generatorManager);

    $this->setGeneratorClass('sfPropelAdmin');
  }
  
  public function getOptionToAction($actionName, $params)
  {
  //return checkbox_tag($actionName, $actionName);
    return "<option value='$actionName'>".$params['name']."</option>";
  }

  public function getAllColumns()
  {
    $phpNames = array();
    foreach ($this->getTableMap()->getColumns() as $column)
    {
      $phpNames[] = new sfPropel13AdminColumn($column->getPhpName(), $column);
    }

    return $phpNames;
  }

  public function getAdminColumnForField($field, $flag = null)
  {
    $phpName = sfInflector::camelize($field);

    return new sfPropel13AdminColumn($phpName, $this->getColumnForPhpName($phpName), $flag);
  }

  // returns a column phpName or null if none was found
  public function getColumnForPhpName($phpName)
  {
    // search the matching column for this column name

    foreach ($this->getTableMap()->getColumns() as $column)
    {
      if ($column->getPhpName() == $phpName)
      {
        return $column;
      }
    }

    // not a "real" column, so we will simulate one
    return null;
  }
  
  public function getColumnFilterTag($column, $params = array())
  {
    $user_params = $this->getParameterValue('list.fields.'.$column->getName().'.params');
    $user_params = is_array($user_params) ? $user_params : sfToolkit::stringToArray($user_params);
    $params      = $user_params ? array_merge($params, $user_params) : $params;

    if ($column->isComponent())
    {
      return "get_component('".$this->getModuleName()."', '".$column->getName()."', array('type' => 'list'))";
    }
    else if ($column->isPartial())
    {
      return "get_partial('".$column->getName()."', array('type' => 'filter', 'filters' => \$filters))";
    }

    $type = $column->getType();

    $default_value = "isset(\$filters['".$column->getName()."']) ? \$filters['".$column->getName()."'] : null";
    $unquotedName = 'filters['.$column->getName().']';
    $name = "'$unquotedName'";
  // $params['id'] = "filter_".$params['id'];
    if ($column->isForeignKey())
    {
      $params = $this->getObjectTagParams($params, array('include_blank' => true, 'related_class'=>$this->getRelatedClassName($column), 'text_method'=>'__toString', 'control_name'=>$unquotedName));
      return "object_select_filter_tag($default_value, null, $params)";

    }
    else if ($type == PropelColumnTypes::DATE)
    {
      // rich=false not yet implemented
      $params = $this->getObjectTagParams($params, array('rich' => true, 'calendar_button_img' => sfConfig::get('sf_admin_web_dir').'/images/date.png'));
      return "input_date_range_tag($name, $default_value, $params)";
    }
    else if ($type == PropelColumnTypes::TIMESTAMP)
    {
      // rich=false not yet implemented
      $params = $this->getObjectTagParams($params, array('rich' => true, 'withtime' => true, 'calendar_button_img' => sfConfig::get('sf_admin_web_dir').'/images/date.png'));
      return "input_date_range_tag($name, $default_value, $params)";
    }
    else if ($type == PropelColumnTypes::BOOLEAN)
    {
      $defaultIncludeCustom = '__("yes or no")';

      $option_params = $this->getObjectTagParams($params, array('include_custom' => $defaultIncludeCustom));
      $params = $this->getObjectTagParams($params);

      // little hack
      $option_params = preg_replace("/'".preg_quote($defaultIncludeCustom)."'/", $defaultIncludeCustom, $option_params);

      $options = "options_for_select(array(1 => __('yes'), 0 => __('no')), $default_value, $option_params)";

      return "select_filter_tag($name, $options, $params)";
    }
    else if ($type == PropelColumnTypes::CHAR || $type == PropelColumnTypes::VARCHAR || $type == PropelColumnTypes::LONGVARCHAR)
    {
      $size = ($column->getSize() < 15 ? $column->getSize() : 15);
      $params = $this->getObjectTagParams($params, array('size' => $size));
      return "input_filter_tag($name, $default_value, $params)";
    }
    else if ($type == PropelColumnTypes::INTEGER || $type == PropelColumnTypes::TINYINT || $type == PropelColumnTypes::SMALLINT || $type == PropelColumnTypes::BIGINT)
    {
      $params = $this->getObjectTagParams($params, array('size' => 7));
      return "input_filter_tag($name, $default_value, $params)";
    }
    else if ($type == PropelColumnTypes::FLOAT || $type == PropelColumnTypes::DOUBLE || $type == PropelColumnTypes::DECIMAL || $type == PropelColumnTypes::NUMERIC || $type == PropelColumnTypes::REAL)
    {
      $params = $this->getObjectTagParams($params, array('size' => 7));
      return "input_filter_tag($name, $default_value, $params)";
    }
    else
    {
      $params = $this->getObjectTagParams($params, array('disabled' => true));
      return "input_filter_tag($name, $default_value, $params)";
    }
  }
}

class sfPropel13AdminColumn extends sfAdminColumn
{
  // propel to creole type conversion
  private static $propelToCreole = array(
    PropelColumnTypes::BOOLEAN       => CreoleTypes::BOOLEAN,
    PropelColumnTypes::BINARY        => CreoleTypes::BLOB,
    PropelColumnTypes::BIGINT        => CreoleTypes::BIGINT,
    PropelColumnTypes::BLOB          => CreoleTypes::BLOB,
    PropelColumnTypes::CHAR          => CreoleTypes::CHAR,
    PropelColumnTypes::CLOB          => CreoleTypes::CLOB,
    PropelColumnTypes::DATE          => CreoleTypes::DATE,
    PropelColumnTypes::DECIMAL       => CreoleTypes::DECIMAL,
    PropelColumnTypes::DOUBLE        => CreoleTypes::DOUBLE,
    PropelColumnTypes::FLOAT         => CreoleTypes::FLOAT,
    PropelColumnTypes::INTEGER       => CreoleTypes::INTEGER,
    PropelColumnTypes::LONGVARBINARY => CreoleTypes::LONGVARBINARY,
    PropelColumnTypes::LONGVARCHAR   => CreoleTypes::TEXT,
    PropelColumnTypes::NUMERIC       => CreoleTypes::NUMERIC,
    PropelColumnTypes::REAL          => CreoleTypes::REAL,
    PropelColumnTypes::SMALLINT      => CreoleTypes::SMALLINT,
    PropelColumnTypes::TIMESTAMP     => CreoleTypes::TIMESTAMP,
    PropelColumnTypes::TIME          => CreoleTypes::TIME,
    PropelColumnTypes::TINYINT       => CreoleTypes::TINYINT,
    PropelColumnTypes::VARCHAR       => CreoleTypes::VARCHAR,
    PropelColumnTypes::VARBINARY     => CreoleTypes::VARBINARY
  );
  
  public function getCreoleType()
  {
    return $this->column ? self::$propelToCreole[$this->column->getType()] : null;
  }
}
